package com.example.zp;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class FriendFragment extends Fragment implements View.OnClickListener{

    private View view;
    private Context context;

    ImageView nextIv, playIv, lastIv;
    TextView singerIv, songIv;
    RecyclerView musicRv;

    // 数据源
    List<LocalMusicBean> musics;
    LocalMusicAdapter adapter;

    // 记录当前正在播放的音乐位置
    int currentPosition = -1;
    // 记录暂停音乐时进度条的位置
    int currentPausePositionInSong = 0;
    MediaPlayer mediaPlayer;

    public FriendFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.tab_friend, container, false);
        initView(view);
        mediaPlayer = new MediaPlayer();
        musics = new ArrayList<>();
        // 创建适配器
        context = getActivity();
        adapter =  new LocalMusicAdapter(context, musics);
        musicRv.setAdapter(adapter);
        // 设置布局管理器 context, 布局管理器垂直布局, 不反转
        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        musicRv.setLayoutManager(layoutManager);
        // 加载本地数据源
        loadLocalMusicData();
        // 设置每一项的点击事件
        setEventListener();
        return view;
    }

    // 初始化控件的函数
    private void initView(View view) {
        nextIv = view.findViewById(R.id.local_music_bottom_iv_next);
        playIv = view.findViewById(R.id.local_music_bottom_iv_play);
        lastIv = view.findViewById(R.id.local_music_bottom_iv_last);
        singerIv = view.findViewById(R.id.local_music_bottom_tv_singer);
        songIv = view.findViewById(R.id.local_music_bottom_tv_song);
        musicRv = view.findViewById(R.id.local_music_rv);

        nextIv.setOnClickListener(this);
        playIv.setOnClickListener(this);
        lastIv.setOnClickListener(this);
    }

    // 加载本地存储当中的音乐mp3文件
    private void loadLocalMusicData() {
        // 1. 获取ContentResolver对象
        ContentResolver resolver = context.getContentResolver();
        // 2. 获取本地音乐存储的地址
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        // 3. 查询地址
        Cursor cursor = resolver.query(uri, null, null, null, null);
        // 4. 遍历cursor
        int id = 0;
        while (cursor.moveToNext()) {
            String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            id++;
            String sid = String.valueOf(id);
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
            String time = dateFormat.format(new Date(duration));
            // 将一行中的数据封装到对象中
            LocalMusicBean musicBean = new LocalMusicBean(sid, song, singer, time, path);
            musics.add(musicBean);
        }
        // 数据源变化, 提醒适配器更新
        adapter.notifyDataSetChanged();
    }

    // 设置每一项的点击事件
    private void setEventListener() {
        adapter.setOnItemClickListener(new LocalMusicAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                currentPosition = position;
                LocalMusicBean musicBean = musics.get(position);
                // 设置底部显示的歌曲和歌手
                playMusicByBean(musicBean);
            }
        });
    }

    // 根据传入对象 播放音乐
    private void playMusicByBean(LocalMusicBean musicBean) {
        singerIv.setText(musicBean.getSinger());
        songIv.setText(musicBean.getSong());
        stopMusic();
        // 重置多媒体播放器
        mediaPlayer.reset();
        // 设置新的播放路径
        try {
            mediaPlayer.setDataSource(musicBean.getPath());
            playMusic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 停止音乐播放
    private void stopMusic() {
        if (mediaPlayer != null) {
            currentPausePositionInSong = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            // 切换为播放按钮
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    // 播放音乐
    private void playMusic() {
        // 从停止到播放
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            if (currentPausePositionInSong == 0) {
                // 从头开始播放
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                // 从暂停到播放
                mediaPlayer.seekTo(currentPausePositionInSong);
                mediaPlayer.start();
            }
            playIv.setImageResource(R.mipmap.icon_pause);
        }
    }

    // 暂停音乐
    private void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            currentPausePositionInSong = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.local_music_bottom_iv_last:
                if (currentPosition == 0) {
                    Toast.makeText(context, "已经是第一首了，没有上一曲! ", Toast.LENGTH_SHORT).show();
                    return;
                }
                currentPosition -= 1;
                playMusicByBean(musics.get(currentPosition));
                break;
            case R.id.local_music_bottom_iv_next:
                if (currentPosition == musics.size() - 1) {
                    Toast.makeText(context, "已经是最后一首了，没有下一曲! ", Toast.LENGTH_SHORT).show();
                    return;
                }
                currentPosition += 1;
                playMusicByBean(musics.get(currentPosition));
                break;
            case R.id.local_music_bottom_iv_play:
                // 未选中播放的音乐
                if (currentPosition == -1) {
                    Toast.makeText(context, "请选择需要播放的音乐", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mediaPlayer.isPlaying()) {
                    // 此时处于播放状态, 需要暂停
                    pauseMusic();
                } else {
                    // 未播放音乐, 点击开始播放音乐
                    playMusic();
                }
                break;
        }
    }
}
